package middle;

public class Solution_6 {

    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        char[][] res = new char[numRows][s.length()];
        int[] indexes = new int[numRows];
        int r = 0;
        boolean direct = true;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            res[r][indexes[r]++] = chars[i];

            if (direct) {
                if (r + 1 == numRows) {
                    r--;
                    direct = false;
                } else {
                    r++;
                }
            } else {
                if (r == 0) {
                    r++;
                    direct = true;
                } else {
                    r--;
                }
            }
        }
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < res.length; i++) {
            buffer.append(res[i], 0, indexes[i]);
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        Solution_6 model = new Solution_6();
        System.out.println(model.convert("PAYPALISHIRING", 3));// PAHNAPLSIIGYIR
        //        System.out.println(model.convert("PAYPALISHIRING", 4));// PINALSIGYAHRPI
        //        System.out.println(model.convert("A", 1));// PINALSIGYAHRPI
        //        System.out.println(model.convert("AA", 1));// PINALSIGYAHRPI
    }
}
